package com.xiangyueEducation.uploaderCloud.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiangyueEducation.uploaderCloud.context.BaseContext;
import com.xiangyueEducation.uploaderCloud.mapper.UserMapper;
import com.xiangyueEducation.uploaderCloud.pojo.entity.User;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import com.xiangyueEducation.uploaderCloud.utils.JwtHelper;
import com.xiangyueEducation.uploaderCloud.utils.Result;
import com.xiangyueEducation.uploaderCloud.utils.JwtHelper;
import com.xiangyueEducation.uploaderCloud.utils.Result;
import com.xiangyueEducation.uploaderCloud.utils.enums.ResultCodeEnum;
import com.xiangyueEducation.uploaderCloud.utils.enums.ResultCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;


@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtHelper jwtHelper;
    @Resource
    UserMapper userMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }
        String token = request.getHeader("token");
        try {
            if (!jwtHelper.isExpiration(token)){
                //未过期，验证身份
                // 根据具体的URL路径来决定哪些方法对学生或老师放行
                String path = request.getRequestURI();
                //直接读取用户的身份
                User currentUser = BaseContext.getCurrentUser();
                if (currentUser==null){
                currentUser = userMapper.selectById(jwtHelper.getUserId(token));
                BaseContext.setCurrentUser(currentUser);
                }
                Integer roleId = currentUser.getRoleId();
                boolean isStudent=roleId.equals(1);//1是学生
                boolean isTeacher=roleId.equals(0);//0是老师
                if ((isStudent && (path.contains("student")||path.contains("all")))||path.contains("login")) {
                    // 学生可以访问的路径
                    return true;
                } else if (isTeacher && (path.contains("teacher")||path.contains("all"))){
                    // 老师可以访问的路径
                    return true;
                } else if((isStudent &&  path.contains("teacher"))
                        ||(isTeacher && path.contains("student"))
                        ||(!isTeacher&&!isStudent)){
                    //老师访问了学生的接口
                    Result fail = Result.build(null, ResultCodeEnum.USER_ROLE_ERROR);
                    ObjectMapper objectMapper = new ObjectMapper();
                    String json = objectMapper.writeValueAsString(fail);
                    response.setContentType("application/json;charset=UTF-8");
                    response.getWriter().print(json);
                    return false;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("tokenIsNullException="+e.getMessage());
        }
        Result fail = Result.build(null, ResultCodeEnum.NOT_LOGIN);
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(fail);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().print(json);
        return false;
    }
}
